package com.cedarhd.finance.msg.domain.repository.specification;

import com.cedarhd.finance.msg.domain.entity.Point;
import com.cedarhd.finance.msg.dto.PointQueryDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;

/**
 * @author Evan
 * @date 2018/3/26
 */
public class PointSpecification {
    public static Specification<Point> buildFromDTO(PointQueryDTO dto){
        return (root, query, builder) -> {

            ArrayList<Predicate> list = new ArrayList<>();

            if (StringUtils.isNotBlank(dto.getUserPhone())) {
                list.add(builder.like(root.get("userPhone"), "%"+dto.getUserPhone()+"%"));
            }

            if(dto.getPointType() != null){
                list.add(builder.equal(root.get("pointType"),dto.getPointType()));
            }

            if(StringUtils.isNotBlank(dto.getStartDay())){
                list.add(builder.greaterThanOrEqualTo(root.get("recordDate"),dto.getStartDay()));
            }

            if(StringUtils.isNotBlank(dto.getEndDay())){
                list.add(builder.lessThanOrEqualTo(root.get("recordDate"),dto.getEndDay()));
            }

            Predicate[] predicates = new Predicate[list.size()];
            predicates = list.toArray(predicates);

            return builder.and(predicates);
        };
    }
}
